package thinkinjava1.ch14;

import java.applet.Applet;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

/**
 * Created by BobbyGu on 2017/2/27.
 */
class Ticker extends Thread {
    private Button button = new Button("Toggle");
    private TextField textField = new TextField(10);
    private int count = 0;
    private boolean runFlag = true;

    public Ticker(Container c) {
        button.addActionListener(new ToggleL());
        Panel p = new Panel();
        p.add(textField);
        p.add(button);
        c.add(p);
    }

    class ToggleL implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            runFlag = !runFlag;
        }
    }

    public void run() {
        while (true) {
            if (runFlag)
                textField.setText(Integer.toString(count++));
            try {
                sleep(100);
            } catch (InterruptedException e) {
            }
        }
    }
}

public class Counter4 extends Applet {
    private Button start = new Button("Start");
    private boolean started = false;
    private Ticker[] s;
    private boolean isApplet = true;
    private int size;

    public void init() {
// Get parameter "size" from Web page:
        if (isApplet)
            size = Integer.parseInt(getParameter("size"));
        s = new Ticker[size];
        for (int i = 0; i < s.length; i++)
            s[i] = new Ticker(this);
        start.addActionListener(new StartL());
        add(start);
    }

    class StartL implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            if (!started) {
                started = true;
                for (int i = 0; i < s.length; i++)
                    s[i].start();
            }
        }
    }

    public static void main(String[] args) {
        Counter4 applet = new Counter4();
        // This isn'textField an applet, so set the flag and
        // produce the parameter values from args:
        applet.isApplet = false;
        applet.size =
                (args.length == 0 ? 5 :
                        Integer.parseInt(args[0]));
        Frame aFrame = new Frame("Counter4");
        aFrame.addWindowListener(
                new WindowAdapter() {
                    public void windowClosing(WindowEvent e) {
                        System.exit(0);
                    }
                });
        aFrame.add(applet, BorderLayout.CENTER);
        aFrame.setSize(200, applet.size * 50 + 20);
        //获取屏幕大小
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        //让窗口居中显示
        aFrame.setLocation(screenSize.width / 2 - aFrame.getWidth() / 2,
                screenSize.height / 2 - aFrame.getHeight() / 2);
        applet.init();
        applet.start();
        aFrame.setVisible(true);
    }
}
